﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Commlibrary.ChinaStockWebService;
using System.Net;
using System.IO;
using System.Collections;

namespace Commlibrary
{
    public class StockHelp
    {

        private Commlibrary.ChinaStockWebService.ChinaStockWebService service = 
            new Commlibrary.ChinaStockWebService.ChinaStockWebService();
        private SQLHelp m_oSqlHelp = null;

        public StockHelp()
        { 
            this.m_oSqlHelp = new SQLHelp("","","","");
        }

        public String[] getStockInfoByCode(String sStockNo)
        {

            //String Url = " http://quote.jrj.com.cn/htmdata/html/" + sStockNo + ".htm";

            //Url = " http://chart.jrj.com/htmdata/KLINE/" + sStockNo + ".js";

            String Url = "http://share.jrj.com.cn/cominfo/AllStock.asp";
            Url = Utility.GetHtml(Url);
//600004.htm>白云机场(600004)
            return service.getStockInfoByCode("sh" + sStockNo);
        }

        public DS_Stock InitDBData()
        {
            DS_Stock dsStock = new DS_Stock();
            try
            {
                try
                {
                    dsStock.M_STOCK.Merge(this.m_oSqlHelp.ExecuteSQLFillDataTable("SELECT STOCK_NO, STOCK_NAME FROM M_STOCK"));
                }
                catch {
                    dsStock.M_STOCK.ReadXml(Const.M_STOCK_XML);
                }


                //dsStock.T_USER_STOCK.ReadXml(Const.T_USER_STOCK_XML);
                //dsStock.M_STOCK.ReadXml(Const.M_STOCK_XML);
                //dsStock.M_STOCK_HISTORY.ReadXml(Const.M_STOCK_HISTORY_XML);
            }
            catch
            {

            }
            return dsStock;
        }

        public void BakupDBData(DS_Stock dsStock)
        {
            try
            {
                if (dsStock != null)
                {
                    dsStock.T_USER_STOCK.WriteXml(Const.T_USER_STOCK_XML);
                    dsStock.M_STOCK.WriteXml(Const.M_STOCK_XML);
                    dsStock.M_STOCK_HISTORY.WriteXml(Const.M_STOCK_HISTORY_XML);
                }
            }
            catch
            {
            }
        }

        public DS_Stock.M_STOCKDataTable GetMStockData()
        {
            DS_Stock.M_STOCKDataTable dtMStock = 
                new DS_Stock.M_STOCKDataTable();

            try
            {
                String Url = "http://share.jrj.com.cn/cominfo/AllStock.asp";
                Url = Utility.GetHtml(Url);
                ArrayList arrStock =
                    Utility.GetMidStringList(Url, Const.GET_STOCKINFO_S, Const.GET_STOCKINFO_E); 

                if (arrStock == null || arrStock.Count == 0) 
                    return null;

                this.m_oSqlHelp.GetConn();
                this.m_oSqlHelp.BeginTran();

                for (int iLoop = 0;iLoop < arrStock.Count;iLoop++)
                {
                    String sSrcString = arrStock[iLoop].ToString();
                    String sStockNo = sSrcString.Substring(0, Const.STOCK_NO_LENGTH);
                    String sStockName = Utility.GetMidString(sSrcString, Const.GET_STOCK_NAME_S, Const.GET_STOCK_NAME_E);
                    
                    this.m_oSqlHelp.ExecuteNonQuery(
                        "INSERT INTO M_STOCK (STOCK_NO, STOCK_NAME) VALUES ('" + sStockNo + "', '" + sStockName + "')");

                    DS_Stock.M_STOCKRow rowNew = dtMStock.NewM_STOCKRow();
                    rowNew.STOCK_NO = sStockNo;
                    rowNew.STOCK_NAME = sStockName;
                    dtMStock.AddM_STOCKRow(rowNew);
                }
                this.m_oSqlHelp.CommitTran();
                this.m_oSqlHelp.CloseConn();

                return dtMStock;
            }
            catch (Exception exp)
            {
                throw exp;
            }
        }

        public void DelMStockHistoryData()
        {
            try
            {
                this.m_oSqlHelp.GetConn();
                this.m_oSqlHelp.ExecuteNonQuery("DELETE FROM M_STOCK_HISTORY");
                this.m_oSqlHelp.CloseConn();
            }
            catch (Exception exp)
            {
                throw exp;
            }
        }

        public Boolean GetMStockHistoryData(String sStockNo)
        {
            try
            {
                if (sStockNo == "600096")
                {
                    String aa = "1";
                }

                String Url = "http://chart.jrj.com/htmdata/KLINE/" + sStockNo + ".js";
                Url = Utility.GetHtml(Url);
                if (Url.Length == 0) return false;

                this.m_oSqlHelp.GetConn();
                this.m_oSqlHelp.BeginTran();

                for (int iLoop = 0; iLoop < Const.MAX_HISTORY_CNT;iLoop ++)
                {
                    String sSrcString = 
                        Utility.GetMidString(
                            Url, 
                            String.Format(Const.GET_STOCK_HISTORY_S, iLoop.ToString()), 
                            Const.GET_STOCK_HISTORY_E);

                    if (sSrcString == null || sSrcString.Length == 0)
                    {
                        continue;
                    }

                    String[] split = sSrcString.Split(new string[] {"  "}, StringSplitOptions.None);
                    if (split.Length == Const.HISTORY_NODE_SIZE)
                    {
                        // \na[79]= \"2009-05-06  开:9.07  高:9.09  低:8.98  收:9.08  量:48592  额:4390.32
                        String sOnDate = split[0];
                        if (sOnDate.Trim().Length == 0)
                        {
                            continue;
                        }

                        String sDayOpenPrice = split[1].Split(new string[] { Const.HISTORY_NODE_SEP }, StringSplitOptions.None)[1];
                        String sDayHighPrice = split[2].Split(new string[] { Const.HISTORY_NODE_SEP }, StringSplitOptions.None)[1];
                        String sDayLowPrice = split[3].Split(new string[] { Const.HISTORY_NODE_SEP }, StringSplitOptions.None)[1];
                        String sDayClosePrice = split[4].Split(new string[] { Const.HISTORY_NODE_SEP }, StringSplitOptions.None)[1];
                        String sDayVolume = split[5].Split(new string[] { Const.HISTORY_NODE_SEP }, StringSplitOptions.None)[1];
                        String sDayAmount = split[6].Split(new string[] { Const.HISTORY_NODE_SEP }, StringSplitOptions.None)[1];

                        try
                        {
                            this.m_oSqlHelp.ExecuteNonQuery(
                                "INSERT INTO M_STOCK_HISTORY ( " +
                                "STOCK_NO, ON_DATE, DAY_OPEN_PRICE, DAY_HIGH_PRICE, DAY_LOW_PRICE, DAY_CLOSE_PRICE, DAY_VOLUME, DAY_AMOUNT ) VALUES ('" +
                                sStockNo + "', CAST('" + sOnDate + "' AS DATETIME), '" + sDayOpenPrice + "', '" + sDayHighPrice + "', '" + sDayLowPrice + "', '" + sDayClosePrice + "', '" + sDayVolume + "', '" + sDayAmount + "')");
                        }
                        catch (Exception exp)
                        {
                            continue;
                        }
                    }
                    else {
                        break;
                    }
                }

                this.m_oSqlHelp.CommitTran();
                this.m_oSqlHelp.CloseConn();

                return true;
            }
            catch (Exception exp)
            {
                throw exp;
            }
        }

        public void DelMStockWorkData()
        {
            try
            {
                this.m_oSqlHelp.GetConn();
                this.m_oSqlHelp.ExecuteNonQuery("DELETE FROM M_STOCK_WORK");
                this.m_oSqlHelp.CloseConn();
            }
            catch (Exception exp)
            {
                throw exp;
            }
        }


        public Boolean PrepareStockWorkData(String sStockNo, int iPiece)
        {
            DateTime[] dtMinMax = this.GetStockHistoryMinMaxDate();

            if (dtMinMax == null)
            {
                return false;
            }

            try
            {
                this.m_oSqlHelp.GetConn();
                this.m_oSqlHelp.BeginTran();

                DateTime dtMinDate = dtMinMax[0];
                DateTime dtMaxDate = dtMinMax[1];

                int iPieceAdded = (dtMaxDate - dtMinDate).Days / iPiece;
                DateTime dtLowDate = dtMinDate;
                DateTime dtHighDate = dtMinDate.AddDays(iPieceAdded);

                for (int iLoop = 0; iLoop < iPiece; iLoop++)
                {
                    if (dtHighDate.CompareTo(dtMaxDate) > 0)
                    {
                        dtHighDate = dtMaxDate;
                    }

                    this.m_oSqlHelp.ExecuteNonQuery(
                        "INSERT INTO M_STOCK_WORK (STOCK_NO, PERIOD_S, PERIOD_E, AVG_PRICE, AVG_VOLUME, AVG_AMOUNT) " +
                        "SELECT STOCK_NO, " +
                        "CAST('" + dtLowDate + "' AS DATETIME), " +
                        "CAST('" + dtHighDate + "' AS DATETIME), " +
                        "CAST(AVG(CAST((DAY_OPEN_PRICE + DAY_HIGH_PRICE + DAY_LOW_PRICE + DAY_CLOSE_PRICE) / 4 AS DECIMAL(10, 2))) AS DECIMAL(10, 2)), " +
                        "AVG(DAY_VOLUME), " +
                        "CAST(AVG(DAY_AMOUNT) AS DECIMAL(18, 2)) " +
                        "FROM M_STOCK_HISTORY " +
                        "WHERE ON_DATE >= CAST('" + dtLowDate + "' AS DATETIME) " +
                        "AND ON_DATE <= CAST('" + dtHighDate + "' AS DATETIME)" +
                        "GROUP BY STOCK_NO");

                    dtLowDate = dtHighDate;
                    dtHighDate = dtHighDate.AddDays(iPieceAdded);
                }

                this.m_oSqlHelp.CommitTran();
                this.m_oSqlHelp.CloseConn();

                return true;
            }
            catch (Exception exp)
            {
                this.m_oSqlHelp.RollBackTran();
                throw exp;
            }
        }

        public DateTime[] GetStockHistoryMinMaxDate()
        {

            try
            {
                this.m_oSqlHelp.GetConn();

                int iRecordCnt = Convert.ToInt32(this.m_oSqlHelp.ExecuteScalar("SELECT COUNT(STOCK_NO) FROM M_STOCK_HISTORY"));

                if (iRecordCnt == 0)
                {
                    return null;
                }

                DateTime dtMaxDate = Convert.ToDateTime(this.m_oSqlHelp.ExecuteScalar("SELECT MAX(ON_DATE) FROM M_STOCK_HISTORY"));
                DateTime dtMinDate = Convert.ToDateTime(this.m_oSqlHelp.ExecuteScalar("SELECT MIN(ON_DATE) FROM M_STOCK_HISTORY"));

                this.m_oSqlHelp.CloseConn();

                return new DateTime[] { dtMinDate, dtMaxDate };
            }
            catch (Exception exp)
            {
                this.m_oSqlHelp.RollBackTran();
                throw exp;
            }
        }
        /*
        public static DS_Stock.M_STOCK_WORKDataTable GetMStockWorkData(DS_Stock.M_STOCK_HISTORYDataTable dtHistory)
        {
            DS_Stock.M_STOCK_WORKDataTable dtWork = new DS_Stock.M_STOCK_WORKDataTable();

            if (dtHistory.Rows.Count > 0)
            { 
               //dtHistory.Select("SUM(DAY_OPEN_PRICE + DAY_HIGH_PRICE + DAY_LOW_PRICE + DAY_CLOSE_PRICE)")
            }
        }
         * */
    }
}
